<template>
  <div>
    <a-card v-if="isMedicalInsurance">
      <a-radio-group
        v-model:value="tabActiveKey"
        button-style="solid"
        :size="isSmallScreen ? 'middle' : 'large'"
        class="flex justify-center mb-2"
        @change="onTabRadioChange"
      >
        <a-radio-button v-for="item in filterType()" :key="item.name" class="w-[120px] !flex-none text-center" :value="item.name">
          {{ props.businessType === '门诊发药' && item.name === '自费' ? '全部' : item.name }}
        </a-radio-button>
      </a-radio-group>
      <div v-if="tabActiveKey === '特殊人员'" class="flex justify-between overflow-auto">
        <a-form class="form-style-flex items-center overflow-x-auto" :label-col="{ style: { width: '90px' } }">
          <a-form-item label="人员类别" class="!mb-0">
            <a-select v-model:value="formState.retiredCadreType" :options="[{ value: 1, label: '离休干部' }]" placeholder="请选择" class="!w-48" />
          </a-form-item>
          <a-form-item label="" class="ml-4 !mb-0">
            <a-input v-model:value="formState.retiredCadre" placeholder="离休干部证号" class="w-[200px]" />
          </a-form-item>
        </a-form>
        <a-button type="primary" class="mx-4" @click="onReadCard">读卡</a-button>
      </div>

      <div v-else-if="tabActiveKey !== '自费'" class="flex justify-between overflow-auto">
        <a-form class="form-style-flex items-center overflow-x-auto" :label-col="{ style: { width: '90px' } }">
          <a-input v-if="tabActiveKey === '电子凭证'" v-model:value="formState.ck" placeholder="请扫描电子凭证" class="w-[200px]" />
          <a-input v-if="tabActiveKey === '磁卡'" v-model:value="formState.ck" placeholder="请刷磁卡" class="w-[200px]" />
          <LabelValue
            label="社保卡号"
            label-class="font-bold"
            class="font-bold mx-2"
            :value-class="!isgb && formState.kh ? 'text-blue-600 cursor-pointer underline' : ''"
            :width="220"
            :value="formState.kh"
            @click="onOpenFiveModal"
          />
          <a-form-item v-if="businessType === '门诊挂号'" label="医疗类别" class="!mb-0 mr-4">
            <SelectItem
              v-model:value="formState.medType"
              class="!w-48"
              select-first
              type="med_type"
              :params="{ type: moduleType }"
              trigger="init"
              placeholder="请选择"
              @change="onChangeMedType"
            />
          </a-form-item>
          <LabelValue v-else label="医疗类别" label-class="font-bold" class="font-bold mr-2" :width="180" :value="formState.medTypeName" />
          <LabelValue label="身份证号" label-class="font-bold" class="font-bold mr-2" :width="240" :value="formState.sfzh" />
          <LabelValue label="险种类别" label-class="font-bold" class="font-bold mr-2" :width="200" :value="formState.insutypeName" />
          <a-form-item v-if="businessType === '门诊挂号'" label="门诊慢特病" class="!mb-0 mr-2">
            <a-select v-model:value="formState.dise_codg" :options="feeDetails" placeholder="请选择" allow-clear class="!w-48" @change="emitForm()" />
          </a-form-item>
          <LabelValue v-else label="门诊慢特病" label-class="font-bold" class="font-bold" :width="180" :value="formState.dise_codg" />
          <LabelValue
            v-if="businessType === '门诊挂号' || businessType === '门诊收费' || businessType === '门诊发药' || businessType === '门诊退药'"
            label="账户余额"
            label-class="font-bold"
            class="font-bold"
            :width="180"
            :value="formatAmount(formState.balc)"
          />
          <LabelValue
            v-if="businessType === '门诊挂号' || businessType === '门诊收费' || businessType === '门诊发药' || businessType === '门诊退药'"
            label="参保单位"
            label-class="font-bold"
            class="font-bold"
            :width="180"
            :value="formState.emp_name"
          />
          <a-form-item
            v-if="
              (tabActiveKey === '社保卡' || tabActiveKey === '身份证' || tabActiveKey === '电子凭证') && getSystemConfig('IS_SHOW_INDUSTRIAL INJURY') === '1'
            "
            label="工伤"
            :label-col="{ style: { width: '40px' } }"
            class="!mb-0 mr-2"
          >
            <a-switch v-model:checked="formState.indInjury" class="mr-4" />
            <a-input v-model:value="formState.indInjuryNum" :disabled="!formState.indInjury" placeholder="工伤认定号" allow-clear class="w-[140px]" />
          </a-form-item>
          <a-button type="primary" class="mx-4" @click="onReadCard">读卡</a-button>
          <a-form-item v-if="inAreaCode === '02' && tabActiveKey === '身份证'" class="!mb-0 mr-2">
            <a-input v-if="businessType !== '门诊挂号'" v-model:value="idNumber" placeholder="请输入身份证号" />
          </a-form-item>
          <a-button v-if="inAreaCode === '02' && tabActiveKey === '身份证'" type="primary" class="mx-2" @click="onRegisterNoCard">无卡识别</a-button>
          <slot name="extra"></slot>
        </a-form>
        <slot name="rightBtn"></slot>
      </div>
      <slot v-else name="selfCost"></slot>
    </a-card>
    <a-card v-else>
      <slot name="selfCost"></slot>
    </a-card>
    <!-- 账户查询六期 -->
    <AccountQuerySix v-model:open="accountQuerySixOpen" :resource-data="formState" @ok="onSelectCHS" />
    <!-- 账户查询上海医保五期 -->
    <AccountQueryFive v-model:open="accountQueryFiveOpen" :resource-data="formState" />
  </div>
</template>
<script setup>
import { message } from 'ant-design-vue'

import useUserStore from '@/store/user'
import { formatAmount } from '@/utils/format'
import AccountQuerySix from './AccountQuerySix'
import AccountQueryFive from './AccountQueryFive.vue'

const props = defineProps({
  businessType: {
    type: String,
    default: ''
  },
  callBackData: {
    type: Object,
    default: () => ({})
  },
  moduleType: {
    type: String,
    default: '门诊'
  },
  pageInfo: {
    type: Object,
    default: () => ({})
  }
})
const { empId } = useUserStore()
const emit = defineEmits(['update:open', 'tabChange', 'read', 'change'])
const formState = ref({
  kh: '',
  medType: getSystemConfig('DEFAULT_MI_OUTP_MEDICAL_TYPE_CODE'), //医保挂号默认医疗类别代码
  bigIll: false,
  bigIllNum: undefined,
  insutype: '',
  insutypeName: ''
})
const isMedicalInsurance = ref(false) //是否启用医保
const inAreaCode = ref('00') //00:国家医保101:上海医保 默认为 00
const tabActiveKey = ref('自费')
const readCardSettingStr = ref('') //调用壳使用的json
const jsonStr = ref('') //调用壳返回的JSON
const loginUserDepartment = ref({})
const isgb = ref(true) //true 国平  false  上海五期
const accountQueryFiveOpen = ref(false)
const idNumber = ref('')
const cardTypeEnum = {
  自费: {
    mdtrtCertType: '0001',
    area: '*'
  },
  社保卡: {
    mdtrtCertType: '03',
    area: '*'
  },
  身份证: {
    mdtrtCertType: '02',
    area: '*'
  },
  电子凭证: {
    mdtrtCertType: '01',
    area: '*'
  },
  刷脸授权: {
    mdtrtCertType: '01',
    area: '00'
  },
  终端扫码: {
    mdtrtCertType: '01',
    area: '00'
  },
  磁卡: {
    mdtrtCertType: '00',
    area: '01'
  },
  特殊人员: {
    mdtrtCertType: '06',
    area: '01'
  }
}

const onReset = () => {
  formState.value = {
    kh: '',
    retiredCadreType: 1,
    medType: getSystemConfig('DEFAULT_MI_OUTP_MEDICAL_TYPE_CODE'), //医保挂号默认医疗类别代码
    bigIll: false,
    bigIllNum: undefined,
    insutype: '',
    insutypeName: ''
  }
  idNumber.value = ''
}
const businessEmnu = {
  门诊挂号: '01101',
  门诊收费: '01301',
  门诊退费: '01301',
  门诊退号: '01301',
  门诊发药: '01302',
  门诊退药: '01302',
  住院结算: '01301',
  出院退费: '01301'
}
const feeDetails = ref([])
const onTabRadioChange = async () => {
  //标签栏切换事件
  let businessType = 0
  if (tabActiveKey.value === '身份证' || tabActiveKey.value === '社保卡') {
    businessType = 1
  } else if (['电子凭证', '刷脸授权', '终端扫码'].includes(tabActiveKey.value)) {
    businessType = businessEmnu[props.businessType]
  } else if (tabActiveKey.value === '磁卡') {
    businessType = '00'
  }
  if (tabActiveKey.value !== '自费') {
    const res = await post('/outp/mzdj/getMedicareCardSettinglnfo', { businessType, officeid: loginUserDepartment.value.ksdm })
    if (res.code !== 0) return message.error(res.msg)
    readCardSettingStr.value = res.data
  } else {
    readCardSettingStr.value = ''
    businessType = 0
    idNumber.value = ''
    formState.value = {
      retiredCadreType: 1,
      kh: '',
      medType: getSystemConfig('DEFAULT_MI_OUTP_MEDICAL_TYPE_CODE'), //医保挂号默认医疗类别代码
      bigIll: false,
      bigIllNum: undefined,
      insutype: '',
      insutypeName: ''
    }
  }
  emit('tabChange', tabActiveKey.value)
}
const accountQuerySixOpen = ref(false)
const onReadCard = async () => {
  if (tabActiveKey.value === '社保卡') {
    jsonStr.value = window.openExe?.readYBK(readCardSettingStr.value) //调用壳
  } else if (tabActiveKey.value === '身份证') {
    jsonStr.value = window.openExe?.readSFZ(readCardSettingStr.value) //调用壳
  } else if (tabActiveKey.value === '磁卡') {
    jsonStr.value = window.openExe?.readCK(formState.value.ck, readCardSettingStr.value) //调用壳
  } else if (tabActiveKey.value === '电子凭证') {
    jsonStr.value = window.openExe?.readDZPZ(formState.value.ck, readCardSettingStr.value) //调用壳
  } else if (tabActiveKey.value === '刷脸授权' || tabActiveKey.value === '终端扫码') {
    // const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
    // if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
    const params = JSON.parse(readCardSettingStr.value)
    const paramsJson = JSON.stringify({
      ...params,
      fficeid: loginUserDepartment.value.ksdm,
      officename: loginUserDepartment.value.ksmc,
      slurl: getSystemConfig('FACE_SWIPING_URL')
    })
    jsonStr.value = tabActiveKey.value === '刷脸授权' ? window.openExe?.readSL(paramsJson) : window.openExe?.readSLSM(paramsJson) //刷脸
  } else if (tabActiveKey.value === '特殊人员') {
    if (!formState.value.retiredCadre) return message.error('请输入证号')
    const { code, data, msg } = await post('/outp/oupCharge/getObtainExpenseBrxx', {
      retiredCadreType: formState.value.retiredCadreType,
      retiredCadre: formState.value.retiredCadre
    })
    if (code !== 0) return message.error(msg || '获取特殊人员信息失败')
    if (data?.brId) {
      emit('read', { ...formState.value, brId: data?.brId, ybkResonse: { br_id: data?.brId }, isgb: isgb.value })
    } else {
      message.warning('暂无患者信息')
    }
    return
  }
  if (!window.openExe) {
    // jsonStr.value =
    //   '{"ybkRquese":{"cardtype":"1","carddata":""},"ybkResonse":{"xb":"女","sfzh":"310104195701174561","lxdh":"65537984","txdz":"淮海中路1799号","yzbm":"200233","klbbz":"1","kh":"D06073096","xm":"张美芳","zhbz":"2000000000000000","dnzhye":0.0,"lnzhye":0.0,"mzzfdxjzfljs":300.0,"zyzfxxzfljs":1200.0,"mzzfdde":300.0,"zyzfdde":1200.0,"tczffdxde":610000.0,"qfxsfdxxfylj":24274.97,"jlch":"100806419510","mzylbkdd":"","br_id":"0100014351","xzqh":"","ybsqjmbz":"1"}}'
    jsonStr.value =
      '{"ksbm_new":null,"jzpzbh_1101":"320000ecd15n606u7e82223a0a0000b154fcc7","jzpzbh":"320000ecd15n606u7e82223a0a0000b154fcc7","ksbm":"A10","name":"张一凡","zjhm":"41282619990109251X","br_id":"41282619990109251X","shbzkh":"41282619990109251X","cbdqh":null,"hatm_empid":"ZZGH","hatm_zdh":"ZZGH001"}'
  }
  //读卡
  const res = await post('/outp/mzdj/getReadPatientInfo', {
    jsonStr: jsonStr.value,
    mdtrtCertNo: '',
    mdtrtCertType: cardTypeEnum[tabActiveKey.value].mdtrtCertType
  })
  if (res.code !== 0) return message.error(res.msg)
  // data.ybkResonse 是读卡的数据 baseinfo是国家医保返回的数据
  formState.value = {
    ...formState.value,
    brName: res.data?.baseinfo?.psn_name,
    retiredCadreType: 1,
    mdtrt_cert_no: res.data?.mdtrtCertNo,
    mdtrt_cert_type: res.data?.mdtrtCertType,
    ...res.data,
    ...res.data?.baseinfo
  }
  formState.value.kh = res.data.ybkResonse?.kh
  formState.value.brId = res.data.ybkResonse?.br_id
  isgb.value = res.data.isgb
  if (props.businessType === '门诊挂号') {
    setFeeDetails(res.data.feedetails)
    res.data.isgb && onOpenCHSInfo(res.data.yxinsuinfo)
  }
  console.info('🏳️‍🌈 <输出> 【读卡数据】:', formState.value)
  emit('read', { ...formState.value, isgb: isgb.value })
}
//无卡医保业务
const onRegisterNoCard = async () => {
  if (props.businessType === '门诊挂号') {
    if (!props.pageInfo.brName || !props.pageInfo.brSfz) return message.error('请输入患者姓名和身份证号')
  } else {
    if (!idNumber.value) return message.error('请输入身份证号')
  }
  const res = await post('/outp/mzdj/getReadPatientInfo', {
    type: 'GH', //固定写死 后端只判断是否为空
    brName: props.pageInfo.brName,
    brSfz: props.businessType === '门诊挂号' ? props.pageInfo.brSfz : idNumber.value
  })
  if (res.code !== 0) return message.error(res.msg)
  formState.value = {
    ...formState.value,
    retiredCadreType: 1,
    brName: res.data?.baseinfo?.psn_name,
    mdtrt_cert_no: res.data?.mdtrtCertNo,
    mdtrt_cert_type: res.data?.mdtrtCertType,
    ...res.data,
    ...res.data?.baseinfo
  }
  formState.value.kh = res.data.ybkResonse?.kh
  formState.value.brId = res.data.ybkResonse?.br_id
  isgb.value = res.data.isgb
  if (props.businessType === '门诊挂号') {
    setFeeDetails(res.data.feedetails)
    res.data.isgb && onOpenCHSInfo(res.data.yxinsuinfo)
  }
  console.info('🏳️‍🌈 <输出> 【读卡数据】:', formState.value)
  emit('read', { ...formState.value, isgb: isgb.value })
}
const getLoginUserDepartment = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  loginUserDepartment.value = res?.data || {}
}
//弹出选择参保信息
const onOpenCHSInfo = (yxinsuinfo) => {
  if (yxinsuinfo?.length > 1) {
    accountQuerySixOpen.value = true
  } else if (yxinsuinfo?.length === 1) {
    formState.value.insutype = yxinsuinfo[0].insutype
    formState.value.insutypeName = yxinsuinfo[0].insutypeName
    formState.value.balc = yxinsuinfo[0].balc
    formState.value.emp_name = yxinsuinfo[0].emp_name
  } else {
    message.error('未读取到参保信息')
  }
}
//慢特病下拉框
const setFeeDetails = (list = []) => {
  feeDetails.value = list.map((item) => {
    return {
      label: item.opsp_dise_name,
      value: item.opsp_dise_code
    }
  })
  if (list.length > 0) {
    formState.value.dise_codg = list[0].dise_codg
    formState.value.dise_name = list[0].dise_name
  }
}
const filterType = () => {
  // area为01为上海五期医保单独处理  其余按国家医保处理
  if (inAreaCode.value) {
    const tab = []
    for (const key in cardTypeEnum) {
      if (Object.hasOwnProperty.call(cardTypeEnum, key)) {
        const element = cardTypeEnum[key]
        if (inAreaCode.value === '01') {
          if (element.area === '01' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        } else {
          if (element.area === '00' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        }
      }
    }
    return tab
  } else {
    message.error('请联系管理员设置医保区域代码')
    return []
  }
}
const onOpenFiveModal = () => {
  if (!isgb.value && formState.value.kh) accountQueryFiveOpen.value = true
}
// 选择险种类别
const onSelectCHS = (row) => {
  formState.value.insutype = row.insutype
  formState.value.insutypeName = row.insutypeName
  formState.value.balc = row.balc
  formState.value.emp_name = row.emp_name
  emit('change', { ...formState.value, isgb: isgb.value })
}
const onChangeMedType = (value) => {
  formState.value.medType = value
  formState.value.med_type = value
  emitForm()
}
const emitForm = () => {
  emit('change', { ...formState.value, isgb: isgb.value })
}
defineExpose({
  reset: onReset
})

watch(
  () => props.callBackData,
  (val) => {
    formState.value.medTypeName = val.medTypeName
    formState.value.insutypeName = val.insutypeName
    formState.value.dise_codg = val.dise_codg
  },
  { deep: true }
)
const isSmallScreen = window.screen.availWidth < 1600 //是否小屏

onMounted(() => {
  isMedicalInsurance.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
  inAreaCode.value = getSystemConfig('NMI_REGION_CODE') //00:国家医保101:上海医保 默认为 00
  getLoginUserDepartment()
})
</script>
<style lang="less" scoped>
:deep(.ant-form-item-label) {
  font-weight: 600;
}
</style>
